<template>
  <el-dialog :close-on-click-modal="false" append-to-body title="编辑" :visible.sync="visible" width="800px">
    <div class="add-form">
      <el-form ref="refundFromEdit" :model="refundFromEdit" :rules="refundFromEditrules" label-width="120px">
        <el-form-item label="后台单号">
          <span v-if="refundFromEdit.xmbzNo">{{ refundFromEdit.xmbzNo }}</span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="平台单号">
          <span v-if="refundFromEdit.platformNo">{{ refundFromEdit.platformNo }}</span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="是否生产">
          <span v-if="refundFromEdit.isProduction == 1">是</span>
          <span v-else>否</span>
        </el-form-item>
        <el-form-item label="渠道类别">
          <span v-if="refundFromEdit.channelTypeName">{{ refundFromEdit.channelTypeName }}</span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="渠道">
          <span v-if="refundFromEdit.channelName">{{ refundFromEdit.channelName }}</span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="退款原因">
          <RefundReasonSelect ref="RefundReasonSelect" v-model="refundFromEdit.refundReason" size="small" @change="handlerefundReason"></RefundReasonSelect>
        </el-form-item>
        <el-form-item label="退款类型" prop="refundType">
          <RefundTypeSelect ref="RefundTypeSelect" v-model="refundFromEdit.refundType" size="small" placeholder="请选择退款类型" @mounted="handleReasonTypeMounted"></RefundTypeSelect>
        </el-form-item>
        <el-form-item label="蛋糕去向">
          <CakeWhereSelect v-model="refundFromEdit.cakeWhereabouts" size="small" placeholder="请选择蛋糕去向"></CakeWhereSelect>
        </el-form-item>
        <el-form-item label="退款等级">
          <RefundLevelSelect v-model="refundFromEdit.refundGrade" size="small" placeholder="请选择退款等级"></RefundLevelSelect>
        </el-form-item>
        <el-form-item label="退款金额" prop="refundMoney">
          <el-input v-model.trim="refundFromEdit.refundMoney" class="inputType" size="small" style="width:200px"
            onkeyup="value=value.replace(/[^\-?\d.]/g,'')" onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="赔偿规则">
          <el-radio-group v-model="refundFromEdit.compensationMethod">
            <el-radio :label="item.dictKey" v-for='item in compensationList' :key="item.dictKey"
              @change="headlecompensationMethod(item.dictKey, refundFromEdit.goodsPrice / 100)">
              <span> {{ item.dictValue }}</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赔偿金额">
          <span>
            <span>
              <el-input v-model.trim="cakeCompensatePrice" class="inputType" size="small" style="width:100px"
                onkeyup="value=value.replace(/[^\-?\d.]/g,'')"
                onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>
            </span>
          </span>
        </el-form-item>
        <el-form-item label="诚意金">
          <span>
            <el-input v-model.trim="refundFromEdit.sincerityGold" class="inputType" size="small" style="width:100px"
              onkeyup="value=value.replace(/[^\-?\d.]/g,'')"
              onaffterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>&nbsp;&nbsp;&nbsp;元（默认0元）
          </span>
        </el-form-item>
        <el-form-item label="赠送蛋糕">
          <span>
            <el-input v-model.trim="refundFromEdit.giveCakePrice" class="inputType" size="small" style="width:100px"
              onkeyup="value=value.replace(/[^\-?\d.]/g,'')"
              onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>&nbsp;&nbsp;&nbsp;元（默认0元）
          </span>
        </el-form-item>
        <el-form-item label="赠送礼品">
          <span>
            <el-input v-model.trim="refundFromEdit.giveGiftPrice" class="inputType" size="small" style="width:100px"
              onkeyup="value=value.replace(/[^\-?\d.]/g,'')"
              onafterpaste="value=value.replace/[^\-?\d.]/g,'')"></el-input>&nbsp;&nbsp;&nbsp;元（默认0元）
          </span>
        </el-form-item>
        <el-form-item label="申请原因" prop="applyReason">
          <el-input v-model.trim="refundFromEdit.applyReason" type="textarea" size="small" maxlength="50" show-word-limit
            :autosize="{ minRows: 4, maxRows: 6 }" class="w-300"></el-input>
        </el-form-item>
        <el-form-item label="门店" prop="store">
          <el-input v-model.trim="refundFromEdit.store" size="small" type="textarea" maxlength="20" show-word-limit
            :autosize="{ minRows: 4, maxRows: 6 }" class="w-300"></el-input>
        </el-form-item>
        <el-form-item label="退款二维码">
          <div class="d-if">
            <el-upload class="avatar-uploader" action="/api/xmbz-goods/file/upload" :show-file-list="false"
              :on-success="handleAvatarSuccessupdate" :before-upload="beforeAvatarUploadupdate">
              <div v-if="refundFromEdit.refundCode">
                <img :src="refundFromEdit.refundCode" class="avatar">
              </div>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <i v-if="refundFromEdit.refundCode" class="el-icon-delete rm-btn" title="移除"
              @click="handleRemoveRefundCode"></i>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="handlerSaveRefund(refundFromEdit, 'refundFromEdit')" v-show="type !== 'view'"
        :loading="loading">{{ loading ? '提交中...' :
          '提交'
        }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  //接口
  CompensationMethod,
  updateWorkOrderRefund, //退款编辑
} from "@/api/workorder";

export default {
  components: {
  },
  data() {
    return {
      visible: false,
      loading: false,
      type: "add",
      refundFromEdit: {
      },
      refundFromEditrules: {
        refundType: [
          {
            required: true,
            message: "退款类型必填",
            trigger: "change"
          }
        ],
        applyReason: [
          {
            required: true,
            message: "申请原因必填",
            trigger: "blur"
          }
        ],
        store: [
          {
            required: true,
            message: "门店必填",
            trigger: "blur"
          }
        ],
        refundMoney: [
          {
            required: true,
            message: "退款金额必填",
            trigger: "blur"
          }
        ]
        // refundCode: [{
        //   required: true,
        //   message: "请上传二维码",
        //   trigger: "change"
        // }]
      },
      RefundTypeList: [], //退款类型
      GradeList: [], // 退款等级
      compensationList: [], //赔偿方式
      cakeCompensatePrice: '',
    }
  },
  methods: {
    show({ data }) {
      this.clearForm()
      this.refundFromEdit = { ...data } || {}
      this.cakeCompensatePrice = data.cakeCompensatePrice
      this.visible = true
      this.getRefundTypeList(data.refundReasonName);
    },
    clearForm() {
      this.refundFromEdit = {}
      this.$refs.form && this.$refs.form.clearValidate()
    },
    handlerSaveRefund(item, formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          var refundMoneys = "";
          if (item.refundMode == 1) {
            refundMoneys = item.refundMoney;
          }
          if (item.refundMode == 2) {
            var cakePrice = this.cakeCompensatePrice;
            let array1 = [
              item.sincerityGold * 100,
              cakePrice * 100,
              item.giveGiftPrice * 100,
              item.giveCakePrice * 100
            ];
            const reducer = (accumulator, currentValue) =>
              accumulator + currentValue;
            if (item.compensationMethod == 1) {
              refundMoneys = (array1.reduce(reducer) / 100).toFixed(2); //退款金额
            } else if (item.compensationMethod == 2) {
              refundMoneys = (array1.reduce(reducer) / 100).toFixed(2); //退款金额
            } else {
              refundMoneys = (array1.reduce(reducer) / 100).toFixed(2); //退款金额
            }
          }
          if (refundMoneys == "") {
            this.$message({
              type: "warning",
              message: "退款金额不能为空!"
            });
            return false;
          } else if (item.store == "") {
            this.$message({
              type: "warning",
              message: "门店不能为空!"
            });
            return false;
          } else {
            const Saverefund = {
              id: item.id,
              orderId: item.orderId,
              refundReason: item.refundReason, //退款原因
              refundType: item.refundType, // 退款类型
              refundGrade: item.refundGrade, // 退款等级
              cakeWhereabouts: item.cakeWhereabouts,
              refundMode: item.refundMode, // 退款方式
              refundMoney: refundMoneys, //退款金额
              compensationMethod: item.compensationMethod, //赔偿方式
              sincerityGold: item.sincerityGold, //诚意金
              cakeCompensatePrice: this.cakeCompensatePrice, //蛋糕金额
              giveCakePrice: item.giveCakePrice, //赠送的蛋糕价格
              giveGiftPrice: item.giveGiftPrice, //赠送的礼品价格
              applyReason: item.applyReason, //申请原
              store: item.store,
              refundCode: item.refundCode
            };
            // 退款详情保存
            this.$confirm("确定修改好该退款工单信息了吗？, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                updateWorkOrderRefund(Saverefund).then(() => {
                  this.$message({
                    type: "success",
                    message: "修改成功!"
                  });
                  this.$emit('submit')
                  this.visible = false
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消修改"
                });
              });
          }
        }
      });
    },
    handleAvatarSuccessupdate(response) {
      this.refundFromEdit.refundCode = response.data;
    },
    beforeAvatarUploadupdate(file) {
      //退款二维码上传限制
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (file.type !== "image/jpeg" && file.type !== "image/png") {
        this.$message.error("上传头像图片只能是 JPG 格式 与 png格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
    },
    handleRemoveRefundCode() {
      this.refundFromEdit.refundCode = '';
    },
    getRefundTypeList(reasonType) {
      this.$refs.RefundTypeSelect && this.$refs.RefundTypeSelect.getList(reasonType);
    },
    CompensationMethodList() {
      // ****备款状态
      CompensationMethod("").then(response => {
        this.compensationList = response.data.data;
      });
    },
    handlerefundReason(value) {
      if (value) {
        this.refundFromEdit.refundType = "";
        const selectedLabel = this.$refs.RefundReasonSelect.getSelectedLabel()
        this.getRefundTypeList(selectedLabel)
      } else {
        this.$message({
          type: "warning",
          message: "请先选择退款原因!"
        });
        return false;
      }
    },
    headlecompensationMethod(item, goodsPrice) {
      if (item == 1) {
        this.cakeCompensatePrice = goodsPrice;
      } else if (item == 2) {
        this.cakeCompensatePrice = goodsPrice / 2;
      } else if (item == 6) {
        this.cakeCompensatePrice = 0;
      }
    },
    handleReasonTypeMounted() {
      this.getRefundTypeList(this.refundFromEdit.refundReasonName)
    }
  },
  created() {
    this.CompensationMethodList();
  },
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 10px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border: 1px solid #ddd;
  border-radius: 10px;
}

.rm-btn {
  font-size: 24px;
  cursor: pointer;
  margin-left: 10px;

  &:hover {
    color: #409eff;
  }
}
</style>
